package com.zhangtai.modules.controller.admin;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zhangtai.modules.controller.aouthLogin.LoginController;
import com.zhangtai.modules.dao.DimissionInfoDao;
import com.zhangtai.modules.dao.EmployeeInfoDao;
import com.zhangtai.modules.dao.TransferInfoDao;
import com.zhangtai.modules.dto.IndexNumDto;
import com.zhangtai.modules.dto.NoticeListVo;
import com.zhangtai.modules.dto.PreNumDto;
import com.zhangtai.modules.entity.common.NoticeEntity;
import com.zhangtai.modules.entity.employee.DimissionInfoEntity;
import com.zhangtai.modules.entity.employee.EmployeeInfoEntity;
import com.zhangtai.modules.entity.transfer.TransferInfoEntity;
import com.zhangtai.modules.service.common.NoticeService;
import com.zhangtai.modules.vo.NoticeVo;
import com.zhangtai.utils.BeanUtilsMabach;
import com.zhangtai.utils.DateUtils;
import com.zhangtai.utils.PageResult;
import com.zhangtai.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RequestMapping("index")
@RestController
@Api(tags="首页带代办消息接口")
public class IndexInfoController {

    @Autowired
    private NoticeService noticeService;
    @Autowired
    private EmployeeInfoDao employeeInfoDao;
    @Autowired
    private TransferInfoDao transferInfoDao;
    @Autowired
    private DimissionInfoDao dimissionInfoDao;
    @Autowired
    private LoginController loginController;

    @GetMapping("/getMainInfo")
    @ApiOperation(value="数量统计1")
    public R<IndexNumDto> getIndexNum(HttpServletRequest request)throws Exception{
        String monthBegin = DateUtils.getBeginDayOfMonth()+" 00:00:00";
        String monthEnd = DateUtils.getLastDayOfMonth()+" 23:59:59";
        Date date = new Date();
        String yearBegin =DateUtils.format(date,"yyyy") +"-01-01 00:00:00";
        String yearEnd = DateUtils.format(date,"yyyy")+"-12-31 23:59:59";
        IndexNumDto indexNumDto = new IndexNumDto();
        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request,null,false);
        if(!R.isOk.equals(checkR.getStatus())){
            return checkR;
        }

        List<Long> orgIds = (List<Long>) checkR.getData();
        JSONObject  userInfo = loginController.getUserInfo(request).getData();
        String code = userInfo.getString("usercode");
        Long id = userInfo.getLong("id");
        //月入职数
        int monthHireCount = employeeInfoDao.selectCount(new QueryWrapper<EmployeeInfoEntity>().between("hiredate",monthBegin,monthEnd).eq("is_delete",0).eq("is_entry_status",1).and(wra->wra.in(!CollectionUtils.isEmpty(orgIds),"unit_id",orgIds).or().
                eq("principal_user_code",code).or().eq(CollectionUtils.isEmpty(orgIds),"unit_id",null)));
        //年入职人数
        int yearHireCount = employeeInfoDao.selectCount(new QueryWrapper<EmployeeInfoEntity>().between("hiredate",yearBegin,yearEnd).eq("is_delete",0).and(wra->wra.in(!CollectionUtils.isEmpty(orgIds),"unit_id",orgIds).or().
                eq("principal_user_code",code).or().eq(CollectionUtils.isEmpty(orgIds),"unit_id",null)).eq("is_entry_status",1));
        //月实习人数
        int monthTrainerCount = employeeInfoDao.selectCount(new QueryWrapper<EmployeeInfoEntity>().between("hiredate",monthBegin,monthEnd).eq("social_trainee",1).and(wra->wra.in(!CollectionUtils.isEmpty(orgIds),"unit_id",orgIds).or().
                eq("principal_user_code",code).or().eq(CollectionUtils.isEmpty(orgIds),"unit_id",null)).eq("is_entry_status",1));
        //年实习人数
        int yearTrainerCount = employeeInfoDao.selectCount(new QueryWrapper<EmployeeInfoEntity>().between("hiredate",yearBegin,yearEnd).eq("social_trainee",1).eq("is_delete",0).and(wra->wra.in(!CollectionUtils.isEmpty(orgIds),"unit_id",orgIds).or().
                eq("principal_user_code",code).or().eq(CollectionUtils.isEmpty(orgIds),"unit_id",null)).eq("is_entry_status",1));
        //月转正人数
        int monthRegularCount = employeeInfoDao.selectCount(new QueryWrapper<EmployeeInfoEntity>().between("regular_day",monthBegin,monthEnd).eq("is_delete",0).and(wra->wra.in(!CollectionUtils.isEmpty(orgIds),"unit_id",orgIds).or().
                eq("principal_user_code",code).or().eq(CollectionUtils.isEmpty(orgIds),"unit_id",null)).eq("is_regular",1));
        //年转正人数
        int yearRegularCount = employeeInfoDao.selectCount(new QueryWrapper<EmployeeInfoEntity>().between("regular_day",yearBegin,yearEnd).eq("is_delete",0).and(wra->wra.in(!CollectionUtils.isEmpty(orgIds),"unit_id",orgIds).or().
                eq("principal_user_code",code).or().eq(CollectionUtils.isEmpty(orgIds),"unit_id",null)).eq("is_regular",1));
        //月离职人数
        int monthDimissionCount = employeeInfoDao.selectCount(new QueryWrapper<EmployeeInfoEntity>().between("dimission_time",monthBegin,monthEnd).eq("is_delete",0).and(wra->wra.in(!CollectionUtils.isEmpty(orgIds),"unit_id",orgIds).or().
                eq("principal_user_code",code).or().eq(CollectionUtils.isEmpty(orgIds),"unit_id",null)).eq("employeestatus",6));
        //年离职人数
        int yearDimissionCount = employeeInfoDao.selectCount(new QueryWrapper<EmployeeInfoEntity>().between("dimission_time",yearBegin,yearEnd).eq("is_delete",0).and(wra->wra.in(!CollectionUtils.isEmpty(orgIds),"unit_id",orgIds).or().
                eq("principal_user_code",code).or().eq(CollectionUtils.isEmpty(orgIds),"unit_id",null)).eq("employeestatus",6));
        //月调出人数
        int monthTransferCount = transferInfoDao.selectCount(new QueryWrapper<TransferInfoEntity>().between("transfer_date",monthBegin,monthEnd).eq("is_delete",0).and(wra->wra.in(!CollectionUtils.isEmpty(orgIds),"before_department_id",orgIds).or().
                eq("apply_code",code).or().eq(CollectionUtils.isEmpty(orgIds),"before_department_id",null)));
        //年调出人数
        int yearTransferCount = transferInfoDao.selectCount(new QueryWrapper<TransferInfoEntity>().between("transfer_date",yearBegin,yearEnd).eq("is_delete",0).and(wra->wra.in(!CollectionUtils.isEmpty(orgIds),"before_department_id",orgIds).or().
                eq("apply_code",code).or().eq(CollectionUtils.isEmpty(orgIds),"before_department_id",null)));
        indexNumDto.setNumEntryYear(yearHireCount);
        indexNumDto.setNumRegularMonth(monthRegularCount);
        indexNumDto.setNumRegularYear(yearRegularCount);
        indexNumDto.setNumExportMonth(monthTransferCount);
        indexNumDto.setNumExportYear(yearTransferCount);
        indexNumDto.setNumDimissionMonth(monthDimissionCount);
        indexNumDto.setNumDimissionYear(yearDimissionCount);
        indexNumDto.setNumInternshipMonth(monthTrainerCount);
        indexNumDto.setNumInternshipYear(yearTrainerCount);
        indexNumDto.setNumEntryMonth(monthHireCount);
        return R.ok(indexNumDto);
    }

    @GetMapping("/getPreInfo")
    @ApiOperation(value="数量统计2")
    public R<PreNumDto> getPreInfo(HttpServletRequest request) throws  Exception{

        PreNumDto preNumDto = new PreNumDto();

        //获取当前用户角色下公司Id
        R checkR = loginController.checkOrgPermission(request,null,false);
        if(!R.isOk.equals(checkR.getStatus())){
            return checkR;
        }

        List<Long> orgIds = (List<Long>) checkR.getData();
        R u = loginController.getUserInfo(request);
        JSONObject user = (JSONObject) u.getData();
        String userCode = user.getString("usercode");
        //当前日期
        String date= DateUtils.format(new Date(),"yyyy-MM-dd");
        //当前月份
        String month = date.substring(5,7);
        List<Integer> isReinstate = new ArrayList<>();
        isReinstate.add(1);
        isReinstate.add(0);
        isReinstate.add(3);
        List<Integer> status = new ArrayList<>();
        status.add(0);
        status.add(1);
        status.add(2);
        status.add(5);
        //待入职
        int preEntry = employeeInfoDao.selectCount(new QueryWrapper<EmployeeInfoEntity>().eq("is_entry_status",0).eq("is_delete",0).in("is_reinstate",isReinstate).eq("status",3).
                and(wra->wra.in(!CollectionUtils.isEmpty(orgIds),"unit_id",orgIds).or().
                        eq("principal_user_code",userCode).or().eq(CollectionUtils.isEmpty(orgIds),"unit_id",null)));
        //待录用
        int preNew = employeeInfoDao.selectCount(new QueryWrapper<EmployeeInfoEntity>().in("status",status).eq("is_delete",0).in("is_reinstate",isReinstate).
                and(wra->wra.in(!CollectionUtils.isEmpty(orgIds),"unit_id",orgIds).or().
                        eq("principal_user_code",userCode).or().eq(CollectionUtils.isEmpty(orgIds),"unit_id",null)));
        //待转正数
        int preRegular = employeeInfoDao.selectCount(new QueryWrapper<EmployeeInfoEntity>().eq("social_trainee","0").eq("is_regular",0).eq("is_delete",0).and(wra->wra.in(!CollectionUtils.isEmpty(orgIds),"unit_id",orgIds).or().
                eq("principal_user_code",userCode).or().eq(CollectionUtils.isEmpty(orgIds),"unit_id",null)));
        //待定薪数
        int preSalary = employeeInfoDao.selectCount(new QueryWrapper<EmployeeInfoEntity>().eq("social_trainee","0").eq("is_distribute",0).eq("is_delete",0).and(wra->wra.in(!CollectionUtils.isEmpty(orgIds),"unit_id",orgIds).or().
                eq("principal_user_code",userCode).or().eq(CollectionUtils.isEmpty(orgIds),"unit_id",null)));
        //待签合同数
        int preContract = employeeInfoDao.selectCount(new QueryWrapper<EmployeeInfoEntity>().eq("social_trainee","0").eq("contract_status",0).eq("is_delete",0).and(wra->wra.in(!CollectionUtils.isEmpty(orgIds),"unit_id",orgIds).or().
                eq("principal_user_code",userCode).or().eq(CollectionUtils.isEmpty(orgIds),"unit_id",null)));
        //待离职
        int preDimission = dimissionInfoDao.selectCount(new QueryWrapper<DimissionInfoEntity>().ne("rurnover_status","2").eq("is_delete",0).and(wra->wra.in(!CollectionUtils.isEmpty(orgIds),"unit_id",orgIds).or().
               eq(CollectionUtils.isEmpty(orgIds),"unit_id",null)));
        //本月周年庆员工数
        int preAnniversary = employeeInfoDao.getPreAnniversaryCount(date,month);
        //本月生日员工数
        int preBirthDay = employeeInfoDao.getBirthDayCount(month);
        preNumDto.setPreEntry(preEntry);
        preNumDto.setPreRegular(preRegular);
        preNumDto.setPreSalary(preSalary);
        preNumDto.setPreContract(preContract);
        preNumDto.setPreDimission(preDimission);
        preNumDto.setPreAnniversary(preAnniversary);
        preNumDto.setPreBirthday(preBirthDay);
        preNumDto.setPreNew(preNew);
        return R.ok(preNumDto);
    }

    @PostMapping("/getNotice")
    @ApiOperation(value="条件分页查询通知")
//    @PreAuthorize("hasAuthority('user:notice:get')")
    public R<PageResult<NoticeEntity>> getNoticeList(@RequestBody @Valid NoticeListVo vo, HttpServletRequest request)throws  Exception{
       R r =  loginController.getUserInfo(request);

       if(!R.isOk.equals(r.getStatus())){
           return r;
       }
       JSONObject user = (JSONObject) r.getData();
       String accepterCode = user.getString("usercode");
        PageResult<NoticeEntity> pageResult = noticeService.queryPage(vo.getType(),vo.getMsgType(),
                vo.getNoticeType(),accepterCode,vo.getTitle(),vo.getIsRead(),vo.getIsDone(), vo.getPageNum(), vo.getPageSize());
        return R.ok(pageResult);
    }

    @GetMapping("/getNoticeById")
    @ApiOperation(value="根据id查看通知")
//    @PreAuthorize("hasAuthority('user:notice:get')")
    public R<NoticeEntity> getNoticeById(@RequestParam("id") Long id){
        NoticeEntity byIdE = noticeService.getByIdE(id);
        return R.ok(byIdE);

    }

    @PostMapping("/updateNotice")
    @ApiOperation(value="修改通知已读状态")
//    @PreAuthorize("hasAuthority('user:notice:get')")
    public R updateNotice(@RequestBody @Valid NoticeVo noticeVo){
        NoticeEntity noticeEntity = BeanUtilsMabach.doToDto(noticeVo, NoticeEntity.class);
        return noticeService.updateByIdE(noticeEntity);
    }

    @GetMapping("/getDoToEvent")
    @ApiOperation(value="获取待办")
//    @PreAuthorize("hasAuthority('user:notice:get')")
    public R getToDoEvent(HttpServletRequest request,String dateString) throws  Exception{
        R r =  loginController.getUserInfo(request);
        if(!R.isOk.equals(r.getStatus())){
            return r;
        }
        JSONObject user = (JSONObject) r.getData();
        String accepterCode = user.getString("usercode");
        List<NoticeEntity> noticeEntityList = noticeService.getNoticeByMonth(accepterCode,dateString);
        JSONArray arr = new JSONArray();
        JSONArray o = new JSONArray();
        Date date = null;
        for(NoticeEntity notice:noticeEntityList){
            if(arr.size()==0){
                date = notice.getTodoDate();
            }
            if((arr.size()!=0&&DateUtils.daysBetween(notice.getTodoDate(),date)!=0)||arr.size()==0){
                JSONObject j = new JSONObject();
                j.put("date",DateUtils.format(date,"yyyy-MM-dd"));
                j.put("data",notice);
                arr.add(j);
            }else{
                    o.add(notice);
            }

        }
      return R.ok(arr);
    }
}
